package com.example.dingdong.rest;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.dingdong.daomain.BasicUserEntity;
import com.example.dingdong.daomain.MenuEntity;
import com.example.dingdong.daomain.OrderRecordEntity;
import com.example.dingdong.service.BasicUserService;
import com.example.dingdong.service.MenuService;
import com.example.dingdong.service.OrderService;
import com.example.dingdong.util.CheckRequestUtil;
import com.example.dingdong.util.ExceptionType;
import com.example.dingdong.util.MyException;
import com.example.dingdong.util.TimeFormate;

/**
 * 
 * @ClassName: OrderRest
 * @Description: 
 * @DateTime 2022-03-25 22:26:28
 */
@RestController
@RequestMapping("/web/rest/order/")
public class OrderRest {
	//创建日志
	private static final Logger log = LoggerFactory.getLogger(OrderRest.class);
	
	@Autowired
	private OrderService  orderService;
	@Autowired
	private MenuService  menuService;
	@Autowired
	private BasicUserService userService;
	/**
	 * 
	 * @Title: getAllMenus
	 * @Description: 
	 * @Author coding
	 * @DateTime 2022-03-25 23:07:19
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("getAllOrders")
	public JSONObject getAllMenus(@RequestBody String reqStr) {
		log.info("getAllOrders:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "getAllOrders");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			CheckRequestUtil.checkReqInterface(reqStr, "getAllOrders");
			
			// 获取数据
			List <OrderRecordEntity> orderRecordEntities=  orderService.allOrderInformationData();
			JSONArray data = new JSONArray();
			//遍历返回数据
			for (OrderRecordEntity orderRecordEntity : orderRecordEntities) {
				JSONObject addData = new JSONObject();
				JSONObject options = new JSONObject();
				addData.put("id",orderRecordEntity.getId()); 
				addData.put("key", orderRecordEntity.getId());
				addData.put("createTime", orderRecordEntity.getCeckingInTime());
				addData.put("status", orderRecordEntity.getStatus());
				addData.put("totalPrice", orderRecordEntity.getTotalPrice());
				addData.put("orderNumber",orderRecordEntity.getOriderNumber()); 
				addData.put("address",orderRecordEntity.getBasicUserEntity() !=null ?  orderRecordEntity.getBasicUserEntity().getAddress():""); 
				addData.put("phone",orderRecordEntity.getBasicUserEntity() !=null ?  orderRecordEntity.getBasicUserEntity().getPhone():""); 
				addData.put("ceckingInTime", orderRecordEntity.getCeckingInTime()); 
				data.add(addData);	
				options.put("createTime", orderRecordEntity.getCeckingInTime());
				options.put("orderNumber",orderRecordEntity.getOriderNumber()); 
				options.put("address",orderRecordEntity.getBasicUserEntity() !=null ?  orderRecordEntity.getBasicUserEntity().getAddress():""); 
				options.put("phone",orderRecordEntity.getBasicUserEntity() !=null ?  orderRecordEntity.getBasicUserEntity().getPhone():""); 
				options.put("status", orderRecordEntity.getStatus());
				options.put("phone",orderRecordEntity.getBasicUserEntity() !=null ?  orderRecordEntity.getBasicUserEntity().getPhone():""); 
				options.put("photo", orderRecordEntity.getMenuEntity() !=null ? orderRecordEntity.getMenuEntity().getPhotoPath():"");
				options.put("dishDetails", orderRecordEntity.getMenuEntity() !=null ? orderRecordEntity.getMenuEntity().getDishDetails():"");
				options.put("menuName", orderRecordEntity.getMenuEntity() !=null ? orderRecordEntity.getMenuEntity().getMenuName():"");
				options.put("totalPrice", orderRecordEntity.getTotalPrice());
				addData.put("viewDetails",options); 
			}
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
			response.put("message", data);
		}catch (MyException e) {
			log.error("getAllMenus:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("getAllMenus:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		System.out.println(response.toJSONString());
		System.out.println("getAllOrders接口方法调用完成");
		return return_data;
	}
	@RequestMapping("deleteOrder")
	public JSONObject deleteOrder(@RequestBody String reqStr) {
		log.info("deleteOrder:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "deleteOrder");
		returnData.put("type", "response");
		returnData.put("response", response);
		
		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "deleteOrder");
			
			List<Object> idList = request.getJSONArray("idList");
			if (idList == null || idList.size() == 0) {
				throw new MyException(ExceptionType.NotFound, "请传入idList！");
			}

			/**
			 * 查找数据库中的数据
			 */
			for (Object object : idList) {
				 OrderRecordEntity orderRecordEntity =orderService.getOrderRecords(Long.valueOf(String.valueOf(object)).longValue(), true);
				if  (orderRecordEntity == null) {
					throw new MyException(ExceptionType.LookupDatabaseIsEmpty, "数据库中暂无该数据！");
				}
				/**
				 * 删除数据
				 */
				orderRecordEntity.setDelFlag(false);
			   orderService.savaOrderEntities(orderRecordEntity);
			}
			
			/**
			 * 返回数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("deleteOrder:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("deleteOrder:");
			e.printStackTrace();
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("deleteOrder: " + returnData);
		return returnData;
	}
	/**
	 * 
	 * @Title:getAllDatStatistics
	 * @Description: 数据统计
	 * @Author coding
	 * @DateTime 2022-03-27 10:43:29
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("getAllDatStatistics")
	public JSONObject getAllDatStatistics(@RequestBody String reqStr) {
		log.info("getAllDatStatistics:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "getAllBoardDatas");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			JSONObject req =CheckRequestUtil.checkReqInterface(reqStr, "getAllDatStatistics");
			
			JSONObject message = new JSONObject();
			//获取商户id
			if (req.get("id") == null) {
				throw new MyException("该商户不存在");
			}
			Long id= req.getLong("id");//
			//判断工业园区是否存在
			BasicUserEntity basicUserEntity= userService.getBasicUserEntity(id, true);
			if (basicUserEntity == null) {
				throw new MyException("未查到该商户");
			}
			// 获取当前日期
			Date eTime = new Date();
			// 获取7天前日期
			Calendar theCa = Calendar.getInstance();
			theCa.setTime(eTime);
			theCa.add(theCa.DATE, -6);
			Date sTime = TimeFormate.getDateByFormatDateYMD(TimeFormate.getFormatStrYMDByDate(theCa.getTime())); // 取出信息

			long startTime = TimeFormate.getDateByFormatDateYMD(TimeFormate.getFormatStrYMDByDate(sTime)).getTime();
			long endTime = eTime.getTime();
			
			/**
			 * 获取七日订单量
			 */
			List<Object[]> boardEntities =orderService. getOrderRecordInformation(id,sTime, eTime);
			// 整理信息
			Map<Long, Integer> map = new TreeMap<>();
			JSONArray data = new JSONArray();


			for (long i = startTime; i < endTime; i = i + 86400000) {
				map.put(new Date(i).getTime(), 0);
			}
			//获取七日扫码入园情况
			for (Object[] add : boardEntities) {
				map.put(TimeFormate.getDateByFormatDateYMD(add[0].toString()).getTime(),
						Integer.valueOf(add[1].toString()));
			}
			for (Long add : map.keySet()) {
				JSONObject addData = new JSONObject();
				addData.put("time", add);
				addData.put("number", map.get(add));
				data.add(addData);
			}
			message.put("ordersInRecentSevenDays", data);
			
			
			// 获取当天开始时间和结束时间
			Date start = TimeFormate.getDateByFormatDateYMD(TimeFormate.getFormatStrYMDByDate(new Date()));
			Date end = TimeFormate.getEndTime(new Date());
			// 获取数据菜品
			List <MenuEntity> menuEntities=  menuService.allMenuInformationData();
			//遍历返回数据
			JSONArray data1 = new JSONArray();
			for (MenuEntity menuEntity : menuEntities) {
				JSONObject addData1 = new JSONObject();
				List<OrderRecordEntity> menuList = orderService.getTodayOrdering( menuEntity.getId(),start, end );
				addData1.put("menuName", menuEntity.getMenuName());
				addData1.put("menuTotal",   menuList.size()); 
				data1.add(addData1);
			}
			message.put("menuList", data1);
			/**
			 * 获取七日收益
			 */
			List<Object[]> orList =orderService. getOrderRecordInformation(id,sTime, eTime);
			// 整理信息
			Map<Long, Integer> map3 = new TreeMap<>();
			JSONArray data3 = new JSONArray();


			for (long i = startTime; i < endTime; i = i + 86400000) {
				map3.put(new Date(i).getTime(), 0);
			}
			//获取七日扫码入园情况
			for (Object[] add : orList) {
				map3.put(TimeFormate.getDateByFormatDateYMD(add[0].toString()).getTime(),
						Integer.valueOf(add[1].toString()));
			}
			for (Long add : map.keySet()) {
				JSONObject addData = new JSONObject();
				addData.put("time", add);
				addData.put("number", map.get(add));
				data3.add(addData);
			}
			message.put("earningsInRecentSevenDays", data);
			
			
			/**
			 * 返回前端数据
			 */			
			response.put("res", true);
			response.put("message",message);
		}catch (MyException e) {
			log.error("getAllDatStatistics:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("getAllDatStatistics:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("getAllDatStatistics 接口方法调用完成!");
		return return_data;
	}
	
}
